﻿using AutoMapper;
using BBICMS.Application.InputModels.Products;
using BBICMS.Application.ViewModels;
using BBICMS.Infrastructure.Configs;
using BBICMS.Model;
using BBICMS.Repository;
using BBICMS.Resources;
using BBICMS.ViewModel;
using BBICMS.WebUI.Filters;
using PagedList;
using SIG.Infrastructure.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace BBICMS.WebUI.Areas.Admin.Controllers
{
    [SIGAuth]
    
    public class ProductController : BaseController
    {
        
        #region Products

        public ActionResult Index(int? page = 1)
        {
            
            ProductListVM vm = new ProductListVM();

            vm.PageIndex = (page ?? 1) - 1;
            vm.PageSize = SettingsManager.Product.PageSize;
            ViewBag.PageSizes = new SelectList(Site.PageSizes());
          
            var orgProducts = _unit.Products.GetPagedElements(vm.PageIndex, vm.PageSize, p=>p.Id, false,p=>p.Category);
            List<ProductVM> products = new List<ProductVM>();
            foreach (var item in orgProducts)
            {
                var defaultLang = _unit.Languages.GetAll().OrderByDescending(l => l.IsDefault).ThenBy(l => l.FullName).FirstOrDefault().CultureName;
                var cl = _unit.ProductCategoryLangs.FindBy(l => l.CategoryId == item.CategoryId && l.CultureName == defaultLang).FirstOrDefault();

                ProductVM newProduct = new ProductVM
                {
                    Id = item.Id,
                    ProductNo = item.ProductNo,
                    Active = item.Active,
                    Recommend = item.Recommend,
                    AddedBy = item.AddedBy,
                    AddedDate = item.AddedDate,
                    Thumbnail = item.Thumbnail,
                    ViewCount = item.ViewCount,
                    Lang = item.Lang,                   
                    CategoryTitle = cl!=null?cl.Title:"",
                  
                };

                products.Add(newProduct);
            }

            
            //var pcls = _unit.ProductCategoryLangs.GetFilteredElements(c => c.CultureName == defaultLang, c => c.Category).ToList();
            //var categories = Mapper.Map<List<ProductCategoryLang>, List<ProductCategoryVM>>(pcls);
            //return categories.OrderByDescending(c => c.Importance).ToList();

            vm.TotalCount = _unit.Products.GetAll().Count();

            vm.ProductList = new StaticPagedList<ProductVM>(products, vm.PageIndex + 1, vm.PageSize, vm.TotalCount);

            return View(vm);
        
        }

        public ActionResult Add()
        {
      
            var selectCategories = new SelectList(GetCategories(), "Id", "Title");
            ViewBag.Categories = selectCategories;
            ViewBag.Langs = new SelectList(LanguageHelper.ActiveLanguages(), "CultureName", "FullName");
            var vProductIM = new ProductIM
            {
                Active = true,
                Importance = 0
            };

            return View(vProductIM);
        }


        [HttpPost]
        [ValidateInput(false)]

        public JsonResult Add(ProductIM vm)
        {

            if (ModelState.IsValid)
            {
                var product = Mapper.Map<Product>(vm);
                _unit.Products.Add(product);
                _unit.SaveChanges();

                AR.SetSuccess(string.Format(Messages.AlertCreateSuccess, EntityNames.Product));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            AR.Setfailure(string.Format(Messages.AlertCreateFailure, EntityNames.Product));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        public ViewResult Edit(int id)
         {
           
            var product = _unit.Products.GetById(id);
            if (product != null)
             {
                var selectCategories = new SelectList(GetCategories(), "Id", "Title");
                ViewBag.Categories = selectCategories;
                ViewBag.Langs = new SelectList(LanguageHelper.ActiveLanguages(), "CultureName", "FullName");

                ProductIM vm = Mapper.Map<Product, ProductIM>(product);
                return View(vm);
             }

             return View("NotFound");
          
         }

        [HttpPost]
        [ValidateInput(false)]
        public JsonResult Edit(ProductIM vm)
        {

            if (ModelState.IsValid)
            {
                var vproduct = _unit.Products.GetById(vm.Id);
                var product = Mapper.Map(vm, vproduct);
          
                _unit.Products.Update(product);
                _unit.SaveChanges();

                AR.SetSuccess(string.Format(Messages.AlertUpdateSuccess, EntityNames.Product));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            AR.Setfailure(string.Format(Messages.AlertUpdateFailure, EntityNames.Product));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }
        [HttpPost]
        public JsonResult IsRecommend(int id)
        {
            var product = _unit.Products.GetById(id);
            if (product != null)
            {
                product.Recommend = !product.Recommend;
                _unit.Products.Update(product);
                _unit.SaveChanges();

                AR.SetSuccess(Messages.AlertActionSuccess);
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            AR.Setfailure(Messages.AlertActionFailure);
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        [HttpPost]
        public JsonResult IsActive(int id)
        {
            var product = _unit.Products.GetById(id);
            if (product != null)
            {
                product.Active = !product.Active;
                _unit.Products.Update(product);
                _unit.SaveChanges();

                AR.SetSuccess(Messages.AlertActionSuccess);
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            AR.Setfailure(Messages.AlertActionFailure);
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            Product vProduct = _unit.Products.GetById(id);
            if (vProduct != null)
            {               

                _unit.Products.Delete(vProduct);
                _unit.SaveChanges();

                AR.SetSuccess(string.Format(Messages.AlertDeleteSuccess, EntityNames.Product));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            AR.Setfailure(string.Format(Messages.AlertDeleteFailure, EntityNames.Product));
            return Json(AR, JsonRequestBehavior.DenyGet);
        }
        #endregion

        #region product photos

        // GET: /bbi_Admin/Work/Types

        public ActionResult Photos(int productId)
        {
            ProductPhotoIM photo = new ProductPhotoIM
            {
                ProductId = productId,
                Importance = 0
            };

            ViewBag.Photos = _unit.ProductPhotos.GetAll().Where(p => p.ProductId == productId).OrderByDescending(p => p.Importance).ToList();

            return View(photo);
        }

        


        [HttpPost]

        public JsonResult AddPhoto(ProductPhotoIM vm)
        {

            if (ModelState.IsValid)
            {
                var photo = Mapper.Map<ProductPhoto>(vm);
                _unit.ProductPhotos.Add(photo);
                _unit.SaveChanges();

                AR.SetSuccess(string.Format(Messages.AlertCreateSuccess, EntityNames.ProductPhoto));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            AR.Setfailure(string.Format(Messages.AlertCreateFailure, EntityNames.ProductPhoto));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        
        [HttpPost]
        public JsonResult DeletePhoto(int id)
        {

            ProductPhoto vPhoto = _unit.ProductPhotos.GetById(id);

            if (vPhoto != null)
            {         

                _unit.ProductPhotos.Delete(vPhoto);
                _unit.SaveChanges();

                AR.SetSuccess(string.Format(Messages.AlertDeleteSuccess, EntityNames.ProductPhoto));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            AR.Setfailure(string.Format(Messages.AlertDeleteFailure, EntityNames.ProductPhoto));
            return Json(AR, JsonRequestBehavior.DenyGet);
        }


        #endregion

        #region categories

        // GET: /bbi_Admin/Work/Types

        public ActionResult Categories(int? page)
        {         
            return View(GetCategories());
        }

        public List<ProductCategoryVM> GetCategories()
        {
            var defaultLang = _unit.Languages.GetAll().OrderByDescending(l => l.IsDefault).ThenBy(l => l.FullName).FirstOrDefault().CultureName;
            var pcls = _unit.ProductCategoryLangs.GetFilteredElements(c => c.CultureName == defaultLang, c => c.Category).ToList();
            var categories = Mapper.Map<List<ProductCategoryLang>, List<ProductCategoryVM>>(pcls);
            return categories.OrderByDescending(c=>c.Importance).ToList();
        }


        public ActionResult AddCategory()
        {
            List<ProductCategoryLangIM> pcl = Mapper.Map<List<Language>, List<ProductCategoryLangIM>>(LanguageHelper.ActiveLanguages().ToList());      
          
            var vProductCategory = new ProductCategoryIM
            {
                Active = true,
                Importance = 0,
                ProductCategoryLangs = pcl
            };

            return View(vProductCategory);
        }


        [HttpPost]
        

        public JsonResult AddCategory(ProductCategoryIM vm)
        {
            if (ModelState.IsValid)
            {
                var ProductCategory = new ProductCategory
                {
                    Active = vm.Active,
                    Importance = vm.Importance,
                    ProductCategoryLangs = Mapper.Map<List<ProductCategoryLangIM>, List<ProductCategoryLang>>(vm.ProductCategoryLangs)
                };
                   
                _unit.ProductCategories.Add(ProductCategory);
                _unit.SaveChanges();

                AR.SetSuccess(string.Format(Messages.AlertCreateSuccess, EntityNames.Category));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            AR.Setfailure(string.Format(Messages.AlertCreateFailure, EntityNames.Category));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        public ActionResult EditCategory(int id)
        {
            var category = _unit.ProductCategories.GetFirstOrDefault(c=>c.Id==id,c=>c.ProductCategoryLangs);

            if (category != null)
            {
                ProductCategoryIM ProductCategory = new ProductCategoryIM
                {
                    Active = category.Active,
                    Importance = category.Importance,
                    AddedBy = category.AddedBy,
                    AddedDate = category.AddedDate,
                    UpdatedBy = category.UpdatedBy,
                    UpdatedDate = category.UpdatedDate,
                    ProductCategoryLangs = GetPCategoryLangs(category.ProductCategoryLangs)
                };
                //var ProductCategory = Mapper.Map<ProductCategoryIM>(category);
                return View(ProductCategory);
            }
            return View("NotFound");
        }

        public List<ProductCategoryLangIM> GetPCategoryLangs(IEnumerable<ProductCategoryLang> vm)
        {
            List<ProductCategoryLangIM> result = new List<ProductCategoryLangIM>();
            //  var pcl = vm.ToList();
            IEnumerable<ProductCategoryLangIM> pcl = Mapper.Map<IEnumerable<Language>, IEnumerable<ProductCategoryLangIM>>(LanguageHelper.ActiveLanguages());
            foreach (var cIM in pcl)
            {
                ProductCategoryLangIM pclim = new ProductCategoryLangIM
                {
                    CultureName = cIM.CultureName,
                    FullName = cIM.FullName
                };

                foreach (var v in vm)
                {
                    if (cIM.CultureName.Trim().ToLower() == v.CultureName.Trim().ToLower())
                    {
                        pclim.Title = v.Title;
                        pclim.Description = v.Description;

                    }

                }
                result.Add(pclim);
            }
            return result;
        }

        [HttpPost]

        public JsonResult EditCategory(ProductCategoryIM vm)
        {
            
            if (ModelState.IsValid)
            {
                var category = _unit.ProductCategories.GetById(vm.Id);

                //  var ProductCategory = Mapper.Map<ProductCategory>(ProductCategoryIM);
                category.UpdatedDate = DateTime.Now;
                category.Active = vm.Active;
                category.Importance = vm.Importance;
               
                _unit.ProductCategories.Update(category);

                var pclList = _unit.ProductCategoryLangs.FindBy(l => l.CategoryId == category.Id);

                foreach (var pcl in vm.ProductCategoryLangs)
                {
                    var pclIM = pclList.Where(l => l.CultureName == pcl.CultureName).FirstOrDefault();
                    if (pclIM != null)
                    {
                        pclIM.Title = pcl.Title;
                        pclIM.Description = pcl.Description;
                        _unit.ProductCategoryLangs.Update(pclIM);
                    }
                    else
                    {
                        var vPCLIM = Mapper.Map<ProductCategoryLangIM, ProductCategoryLang>(pcl);
                        //  vPCLIM.CategoryId = vm.Id; 
                        vPCLIM.Category = category;
                        _unit.ProductCategoryLangs.Add(vPCLIM);
                    }
                 
                }
                

                _unit.SaveChanges();

                AR.SetSuccess(string.Format(Messages.AlertUpdateSuccess, EntityNames.Category));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            AR.Setfailure(string.Format(Messages.AlertUpdateFailure, EntityNames.Category));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpPost]
        public JsonResult IsActiveCategory(int id)
        {
            var category = _unit.ProductCategories.GetById(id);
            if (category != null)
            {
                category.Active = !category.Active;
                _unit.ProductCategories.Update(category);
                _unit.SaveChanges();

                AR.SetSuccess(Messages.AlertActionSuccess);
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            AR.Setfailure(Messages.AlertActionFailure);
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        // DELETE: /User/DeleteSite
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult DeleteCategory(int id)
        {

            ProductCategory vType = _unit.ProductCategories.GetById(id);

            if (vType != null)
            {
                //string imgurl = Server.MapPath(vBlog.ImageURL);
                //if (System.IO.File.Exists(imgurl))
                //{
                //    System.IO.File.Delete(imgurl);    //删除缩略图
                //}


                _unit.ProductCategories.Delete(vType);
                _unit.SaveChanges();

                AR.SetSuccess(string.Format(Messages.AlertDeleteSuccess, EntityNames.Category));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            AR.Setfailure(string.Format(Messages.AlertDeleteFailure, EntityNames.Category));
            return Json(AR, JsonRequestBehavior.DenyGet);
        }


        #endregion




        protected override void Dispose(bool disposing)
         {
             this._unit.Dispose();
             base.Dispose(disposing);
         }
    }
}
